package com.backend.system.service.processors.user;

import com.backend.system.beans.user.UserAddOrUpdateReq;
import com.backend.system.common.CustomException;
import com.backend.system.common.RequestHeaderUserInfo;
import com.backend.system.common.RequestHolder;
import com.backend.system.common.annotation.ProcessorBean;
import com.backend.system.common.enums.ActionTypeEnum;
import com.backend.system.common.enums.SexEnum;
import com.backend.system.common.processor.AbstractProcessorTemplate;
import com.backend.system.common.processor.ProcessorContext;
import com.backend.system.dao.entity.User;
import com.backend.system.util.CipherUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 新增或修改用户处理器
 *
 * @author backend-manage
 */
@Slf4j
@Component
@ProcessorBean(action = ActionTypeEnum.USER_ADD_OR_UPDATE)
public class UserAddOrUpdateProcessor extends AbstractProcessorTemplate<UserAddOrUpdateReq, Boolean> {

    private boolean isAddUser;

    private User user;

    @Override
    protected void init(ProcessorContext<UserAddOrUpdateReq> context) {
        user = null;
        UserAddOrUpdateReq req = context.getData();
        isAddUser = Objects.isNull(req.getId());

        // 修改用户时，先查寻用户信息
        if (!isAddUser) {
            user = userService.getById(req.getId());
            if (user == null) {
                throw CustomException.argsError("用户不存在");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handle(ProcessorContext<UserAddOrUpdateReq> context) {
        UserAddOrUpdateReq req = context.getData();
        boolean result;

        // 新增用户
        if (isAddUser) {
            User user = buildAddUser(req);
            result = userService.save(user);
        } else {
            // 修改用户
            user.setProfilePhoto(req.getProfilePhoto());
            user.setAge(req.getAge());
            user.setSex(SexEnum.getInstance(req.getSex()));
            user.setBirthday(req.getBirthday());
            user.setPhone(req.getPhone());
            user.setUsername(req.getUsername());
            result = userService.updateById(user);
        }
        return result;
    }

    private User buildAddUser(UserAddOrUpdateReq req) {
        User user = new User();
        user.setUsername(req.getUsername());
        user.setLoginAccount(req.getLoginAccount());
        user.setPassword(CipherUtil.DEFAULT_PASSWORD);
        user.setProfilePhoto(req.getProfilePhoto());
        user.setAge(req.getAge());
        user.setSex(SexEnum.getInstance(req.getSex()));
        user.setBirthday(req.getBirthday());
        user.setPhone(req.getPhone());

        RequestHeaderUserInfo userInfo = RequestHolder.getUserInfo();
        user.setCreateUserId(userInfo.getLoginId());
        user.setCreateUsername(userInfo.getUsername());
        return user;
    }
}
